package com.example.blog_spring.utils;

import com.example.blog_spring.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;
@Slf4j
public class JwtUtils {
    private static final String secret = "VgKa5bcnQ2cTLrywEQ8drVUAIu/KUsZMRTkA/V6dBGY=";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
    private static final long JWT_EXPIRATION = 60 * 30 * 1000;
    /**
     * 生成token
     */
    public static String generateToken(Map<String, Object> secret){
        String token = Jwts.builder().setClaims(secret)
                .setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))
                .signWith(key).compact();
        return token;
    }

    /**
     * 校验token
     */
    public static Claims judgeToken(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        } catch (Exception e){
            log.error("解析token失败....");
            return claims;
        }
        return claims;
    }

    /**
     * 根据token获取id
     */
    public static Integer getIdByToken(String token){
        Claims claims = judgeToken(token);
        Integer id = null;
        if(claims != null){
            id = (Integer) claims.get(Constants.TOKEN_ID);
            if(id > 0){
                return id;
            }
        }
        return id;
    }
}
